import {
	Card,
	Breadcrumb,
	Form,
	Button,
	Radio,
	Input,
	Upload,
	Space,
	Select,
	message
} from 'antd'
import { PlusOutlined } from '@ant-design/icons'
import { Link, useSearchParams, useNavigate } from 'react-router-dom'
import ReactQuill from 'react-quill'
import 'react-quill/dist/quill.snow.css'
import { useState, useEffect, useRef } from 'react'


import './index.scss'
import { http } from '@/utils'

const { Option } = Select


const Publish = () => {


	// 添加暂存仓库用于图片切换
	const fileListRef = useRef([])

	// 上传组件处理
	const [fileList, setFileList] = useState([])
	// 上传成功回调
	const onUploadChange = info => {
		const fileList = info.fileList.map(file => {
			if (file.response) {
				return {
					url: file.response.data.url
				}
			}
			return file
		})
		setFileList(fileList)
		fileListRef.current = fileList
	}

	// 切换图片type
	const [imgCount, setImgCount] = useState(1)

	const changeType = e => {
		const count = e.target.value
		setImgCount(count)
		// 设置fileList展示张数
		if (count === 1) {
			const firstImg = fileListRef.current[0]
			setFileList(!firstImg ? [] : [firstImg])
		} else if (count === 3) {
			setFileList(fileListRef.current)
		}
	}

	// 表单提交
	const navigate = useNavigate()

	const onFinish = async (values) => {
		// 数据的二次处理 重点是处理cover字段
		const { type, ...rest } = values
		const data = {
			...rest,
			// 注意：接口会按照上传图片数量来决定单图 或 三图
			cover: {
				type,
				images: fileList.map(item => item.url)
			}
		}
		if (articleId) {
			// 编辑
			await http.put(`/mp/articles/${articleId}?draft=false`, data)
		} else {
			// 新增
			await http.post('/mp/articles?draft=false', data)
		}
		// 跳转列表 提示用户
		navigate('/article')
		message.success(`${articleId ? '更新成功' : '发布成功'}`)
	}

	// 新增编辑判断
	const [params] = useSearchParams()
	const articleId = params.get('id')


	// 频道列表
	const [channels, setChannels] = useState([])
	// 数据回填  id调用接口  1.表单回填 2.暂存列表 3.Upload组件fileList
	const [form] = Form.useForm()
	useEffect(() => {
		async function fetchChannels () {
			const res = await http.get('/channels')
			setChannels(res.data.channels)
		}
		fetchChannels()
		async function getArticle () {
			const res = await http.get(`/mp/articles/${articleId}`)
			const { cover, ...formValue } = res.data
			console.log('打印***formValue', formValue)

			// 格式化封面图片数据
			const imageList = cover.images.map(url => ({ url }))
			setFileList(imageList)
			setImgCount(cover.type)
			fileListRef.current = imageList
			// 动态设置表单数据
			form.setFieldsValue({
				content: formValue.content,
				type: cover.type,
				title: formValue.title,
				channel_id: formValue.channel_id
			})
		}
		if (articleId) {
			// 拉取数据回显
			getArticle()
		}
	}, [articleId, form])

	return (
		<div className="publish">
			<Card

				title={
					<Breadcrumb
						items={[
							{ title: <Link to='/'>首页</Link> },
							{ title: articleId ? '修改文章' : '发布文章' }
						]}
					>
					</Breadcrumb>
				}
			>
				<Form
					labelCol={{ span: 4 }}
					wrapperCol={{ span: 16 }}
					onFinish={onFinish}
					form={form}
					initialValues={{ title: '', channel_id: 1, type: 1, content: '' }}
				>
					<Form.Item
						label="标题"
						name="title"
						rules={[{ required: true, message: '请输入文章标题' }]}
					>
						<Input placeholder="请输入文章标题" style={{ width: 400 }} />
					</Form.Item>

					<Form.Item
						label="频道"
						name="channel_id"
						rules={[{ required: true, message: '请选择文章频道' }]}
					>
						<Select placeholder="请选择文章频道" style={{ width: 200 }}>
							{channels.map(item => (
								<Option key={item.id} value={item.id}>
									{item.name}
								</Option>
							))}
						</Select>
					</Form.Item>

					<Form.Item label="封面">
						<Form.Item name="type">
							<Radio.Group onChange={changeType}>
								<Radio value={1}>单图</Radio>
								<Radio value={3}>三图</Radio>
								<Radio value={0}>无图</Radio>
							</Radio.Group>
						</Form.Item>
						{
							imgCount > 0 && (<Upload
								name="image"
								listType="picture-card"
								className="avatar-uploader"
								showUploadList
								action="http://geek.itheima.net/v1_0/upload"
								fileList={fileList}
								onChange={onUploadChange}
								maxCount={imgCount}
								multiple={imgCount > 1}
							>
								<div style={{ marginTop: 8 }}>
									<PlusOutlined />
								</div>
							</Upload>
							)}
					</Form.Item>

					<Form.Item
						label="内容"
						name="content"
						rules={[{ required: true, message: '请输入文章内容' }]}
					>
						<ReactQuill
							className="publish-quill"
							theme="snow"
							placeholder="请输入文章内容"
						/>
					</Form.Item>

					<Form.Item wrapperCol={{ offset: 4 }}>
						<Space>
							<Button size="large" type="primary" htmlType="submit">
								{articleId ? '修改文章' : '发布文章'}
							</Button>
						</Space>
					</Form.Item>
				</Form>
			</Card>
		</div>
	)
}

export default Publish